<template>
	<view class="container">
		<view class="main">
			<!-- 拉起键盘，且编辑器模式时，不显示 -->
			<input v-model="title" v-if="!(showKeyBoard&&showEditorKeyBoard)" class="titleWrapper" placeholder="请输入标题" />
			<editor :style="{ 'height': editorHeight + 'px' }" 
				class="myEditor"
				placeholder="请输入内容" 
				@statuschange="onContext"
				@input="onInput"
				@focus="modeShow" 
				@blur="modeShowClose"
				@ready="onEditorReady">
			</editor>

			<view class="tabName">
				<image @click="insertImg" class="icon" src="@/static/image/icon_image.png" mode=""></image>
				
				<image v-show="Bold" @click="setBold(false)" class="icon" src="@/static/image/icon_bold_s.png"  mode="">
				</image>
				<image v-show="!Bold" @click="setBold(true)" class="icon" src="@/static/image/icon_bold_n.png"  mode="">
				</image>
				
				<image @click="repeal" class="icon" src="@/static/image/icon_undo.png" mode=""></image>
				<image @click="recover" class="icon" src="@/static/image/icon_redo.png" mode=""></image>
				<view class="line">
					
				</view>
				<view @click="onSave" class="btn">
					完成
				</view>
				
<!-- 				<image v-if="mode" @click="modeShowClose" src="./static/keyboard.png" mode=""></image>
				<image v-else @click="modeShow" src="./static/keyboard.png" mode=""></image> -->
			</view>
		</view>
		
		<!-- 利用rich-text来回显html内容 data是富文本编辑器html的内容-->
		<!-- <rich-text class="ql-editor" :nodes="data"></rich-text> -->
		<!-- uparse解析 -->
		<!--  <u-parse :content="data" @preview="preview" @navigate="navigate" ></u-parse> -->
	</view>
</template>

<script>
	import utils from "@/static/js/utils.js"
	const api = require("@/static/js/api.js");
	
	let that = null
	import {
		mapState,
		mapMutations,
		mapActions,
		mapGetters
	} from 'vuex';
	
	export default {
		data() {
			return {
				showKeyBoard: false, //显示模块 //如果不需要跟随键盘弹出 改为true默认显示
				showEditorKeyBoard: false,
				Bold: false, //变量
				editorCtx: {},
				//键盘高度
				keyboardHeight: 0,
				editorHeight: 0,
				data: "",
				noteId: "",
				cover: "",
				title:"",
				content: "",
				briefly: "",
				doingSave: false
			}
		},
		onLoad(options) {
			var _this = this
			that = this
			
			if (options.id&&options.id.length>0){
			    that.noteId = options.id;
			}else{
			    that.noteId = "";
			}
				
			uni.getSystemInfo({
				success: function(res) {
					//console.log(res.screenHeight); // 屏幕高度，包含导航栏
					console.log("getSystemInfo:", res.windowHeight); // 能够使用的窗口高度，不包含导航栏
					//console.log(res.screenWidth); // 屏幕宽度
					//console.log(res.windowWidth); //  能够使用的窗口宽度
					_this.Height = res.windowHeight;
					_this.editorHeight = _this.Height- uni.upx2px(110)
				}
			});
			//  监听键盘高度变化
			uni.onKeyboardHeightChange((obj) => {
				_this.keyboardHeight = obj
				if (obj.height > 0) {
					_this.editorHeight = _this.Height - obj.height
					setTimeout(() => {
						_this.showKeyBoard = true
					}, 100)
				} else {
					_this.editorHeight = _this.Height - uni.upx2px(110)
					_this.showKeyBoard = false
				}
				console.log("editorHeight:", _this.editorHeight, _this.showKeyBoard)
			})

		},
		
		computed: {
		    ...mapState({
		        hasLogin: state => state.userInfo.hasLogin,
		        isAuthUserInfo: state => state.userInfo.isAuthUserInfo,
		        isAuthPhone: state => state.userInfo.isAuthPhone,
		        isSeller: state => state.userInfo.isSeller,
		        avatarUrl: state => state.userInfo.avatarUrl,
		        nickName: state => state.userInfo.nickName,
		        telephone: state => state.userInfo.telephone,
		        buyerId: state => state.userInfo.buyerObj.id,
		    }),
		},
		
		methods: {
			getNoteDetail(){
				api.getNoteDetail({
					interfaceName: that.noteId,
					param: {			
					}
				}).then(res=>{
					console.log("getNoteDetail", res)
					if (res.success) {
						that.cover = res.data.cover
						that.title = res.data.title
						that.content = res.data.content
						that.editorCtx.setContents({
							html: that.content 
						})
					}	
				})
			},
			
			createNote(){

				
				that.editorCtx.getContents({
					success: function(data) {
						that.content = data.html
						that.briefly = data.text
						api.getNoteCreate({
							param: {	
								cover: that.cover,
								title: that.title,
								content: that.content,
								briefly: that.briefly
							}
						}).then(res=>{
							console.log("createNote", res)
							if (res.success){
								that.noteId = res.data
								uni.showToast({
									icon:"none",
									title: "保存成功"
								})
							}
						}).finally(()=>{
							that.doingSave = false
						})			
					},
				})	
			},
			
			updateNote(){
				that.editorCtx.getContents({
					success: function(data) {
						that.content = data.html
						that.briefly = data.text
						api.getNoteUpate({
							param: {
								id: that.noteId,
								cover: that.cover,
								title: that.title,
								content: that.content,
								briefly: that.briefly
							}
						}).then(res=>{
							console.log("createNote", res)
							if (res.success){
								uni.showToast({
									icon:"none",
									title: "保存成功"
								})
							}
						}).finally(()=>{
							that.doingSave = false
						})		
					},
				})	
			},
			onSave(){
				if (!that.title){
					uni.showToast({
						icon:"none",
						title: "请输入标题"
					})
					return; 
				}
				if (!that.doingSave){
					that.doingSave = true
					if (that.noteId){
						that.updateNote()
					}else{
						that.createNote()
					}
					setTimeout(()=>{
						that.doingSave = false
            uni.navigateBack({
            })
					}, 1000)
				}
			},

			
			
			//  editor 编辑器		
			modeShow() { 
				this.showEditorKeyBoard = true
			},
			
			modeShowClose(){
				this.showEditorKeyBoard = false
			},
			
			onTitle(event){
				// this.title = event.target.value
			},
			
			onEditorReady(e) { //初始化
				var _this = null
				uni.createSelectorQuery().in(this).select('.myEditor').fields({
					context: true
				}, res => {
					this.editorCtx = res.context
					if (that.noteId&&that.noteId.length>0){
						that.getNoteDetail()
					}else{
						res.context.setContents({
							html: this.content
						})
					}
				}).exec()
			},

			repeal() { //撤销
				let that = this
				this.editorCtx.undo({
					success:res=>{
						that.setBoldStatus()
					}
				})
			},
			
			recover() { //恢复
				let that = this
				this.editorCtx.redo({
					success:res=>{
						that.setBoldStatus()
					}
				})
			},
			setBold(status){
				// that.editorCtx.format('bold', 'bold')
				this.Bold = status
				this.setBoldStatus(status)
			},
			setBoldStatus(){
				// this.editorCtx.format('bold', 'bold')
				if (this.Bold ){
					this.editorCtx.format('font-weight', 'bold')
				}else{
					this.editorCtx.format('font-weight', '400')
				}
			},
			
			insertImg() { //插入图片
				let that = this
				uni.chooseImage({
					count: 1,
					success: res => {
						console.log(res)
						//在这里先把封面截图保存到服务器拿到服务器存储地址放在这里
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							utils.uploadImage(res.tempFilePaths[i], that.buyerId, (path)=>{
								if (!that.cover){
									that.cover = path
								}
								this.editorCtx.insertImage({
									src: path, //图片路径 换成服务器地址
									width: '100%',
								})
							})

						}
						that.getCtx()
					}
				})
			},
			
			
			onContext() { //选中内容
				// var  format = this.editorCtx.getSelectionText()
				// console.log("onContext",format)
			},
			onInput(e){
				// console.log("onInput",e)
			},

			// 获取编辑器内容 
			getCtx() {
				var that = this
				that.editorCtx.getContents({
					success: function(data) {
						console.log('编辑器内容', data)									
						// data.html = data.html.replace(/&lt;/g, '<');
						// data.html = data.html.replace(/&gt;/g, '>');
						// that.data = data.html
						
						// var text = `<p style="height: 60px;width: 250px;text-align: center; border: 1px solid #888;">test</p>`
						// that.editorCtx.setContents({
						// 	html: data.html + text
						// })
						//需要把编辑器内的图片/视频地址更换成储存在服务器后的图片/视频路径

						//在要显示的页面，利用rich-text来回显html内容 data是富文本编辑器html的内容
						// <rich-text class="ql-editor" :nodes="data"></rich-text> 
						//这里把编辑器里的视频封面截图替换成了视频
						//uniapp富文本编辑器内不支持video无法显示视频,rich-text可以显示但需要uparse插件解析
						//https://ext.dcloud.net.cn/plugin?id=183 这里有详细教程

						// let reg = /<img[^>]*class=['videothumb"]([^'"]+)[^>]*>/g
						// that.data = data.html.replace(reg,
						// 	'<video id="myVideo" class="videosrc" src="https://mp-2a0f3e44-b47a-4bd5-a925-ba63d3e2a8ab.cdn.bspapp.com/add_file/2023-09-17 172002.mp4"></video>'
						// 	);
						// console.log(that.data)

					}
				})
			},



		}
	}
</script>

<style lang="scss">
	.tabName {
		display: flex;
		justify-content: space-around;
		align-items: center;
		width: 750rpx;
		height: 80rpx;
		background-image: linear-gradient(
			#ffffff, 
			#ffffff), 
		linear-gradient(
			#ececec, 
			#ececec);
		background-blend-mode: normal, 
			normal;
		box-shadow: 0rpx -2rpx 6rpx 0rpx 
			rgba(0, 0, 0, 0.2);
	
		position: absolute;
		bottom: 0;
		left: 0;
		
		.icon{
			width: 40upx;
			height: 41upx;
		}
		.line{
			width: 1px;
			height: 36rpx;
			background-color: #adadad;
		}
		.btn{
			width: 120rpx;
			height: 49rpx;
			background-color: #10d1ed;
			border-radius: 17rpx;	
			text-align: center;
			line-height: 49rpx;
			color: #fff;
			font-size: 28rpx;
		}
	}

	.container {
		width: 100vw;
		height: 100vh;
	}

	/*  */
	.main {
		width: 100%;
		min-height: 820upx;
		max-height: max-content;
		position: relative;
		/* height: max-content; */
	}

	.myEditor {
		min-height: 820upx;
		max-height: max-content;
		/* height: max-content; */
		padding: 0 20upx;
		font-size: 30upx;
		padding-bottom: 90rpx;
	}
	
	.titleWrapper{
		width: 750rpx;
		height: 80rpx;
		padding: 0 20rpx;
		font-size: 40rpx;
		font-weight: bold;
		font-stretch: normal;
		line-height: 80rpx;
		letter-spacing: 0rpx;
		color: #191919;
		margin-bottom: 30rpx;
	}
</style>